import { useEffect, useRef } from "react";
import styles from "./index.module.scss";
import initOption from "./options";
import * as echarts from "echarts";
import { useDispatch, useSelector } from "react-redux";
import { setLayers } from "@/store";
 

export default function EchartsEL(props) {
  const chartRef = useRef();
  const { textColor, xAxisData, seriesData, colorArr } = props;
  const theme = useSelector((state) => state.theme);
  const dispatch = useDispatch();
  const layers = useSelector((state) => {
    return state.layers;
  });
  const openModel = (name) => {
    dispatch(
      setLayers({
        query: {},
        name,
        other: {},
      })
    );
    console.log(layers);
  };
  const getRealData = (myChart, x, y,max) => {
    const pointInGrid = myChart.convertFromPixel({ seriesIndex: 0 }, [x, y]);
    if (pointInGrid[1] > max || pointInGrid[1] < 0) {
      return false;
    } else {
      var xIndex = pointInGrid[0];
      return xAxisData[xIndex];
    }
  };

  useEffect(() => {
    const option = initOption(textColor, xAxisData, seriesData, colorArr);
    const chart = echarts.init(chartRef.current);
    // const max = Math.max(...seriesData);
    // chart.getZr().on("click", (e) => {
    //   const result = getRealData(chart, e.offsetX, e.offsetY,max);
    //   if (result) {
    //     openModel("model29");
    //   }
    // });
    chart.on("click",(params)=>{
      openModel("model29");
    })
    chart.setOption(option);
    return () => {
      chart.dispose();
    };
  }, [theme]);
  return (
    <>
      <div id="main" ref={chartRef} className={styles.echarts}></div>
    </>
  );
}
